﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using EntreeServer.Module;
using EntreeServer.Module.ActionTray;
using EntreeServer.Module.Configuration;
using EntreeServer.Module.Controls;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace ME.SDK.SketchAction
{
    [Guid("05368201-d496-411d-a7c6-fefd78e6bd03")]
    public class AddSketch : ActionProvider
    {

        public override void QueryScope(ActionScopeObject scope, out ActionLaneCollection actionLanes, out ActionItemCollection actionItems)
        {
            actionLanes = null;
            actionItems = new ActionItemCollection();
            // Set up RegEx match for list titles
            string rxm = RegExMatch;
            if (rxm == null || rxm.Trim() == string.Empty) rxm = ".";
            Regex rx = new Regex(rxm);

            //Check scope for Detail screen or Index screen
            if ((scope.ScopeType == ScopeTypes.SharePoint.SPListItem_Details || scope.ScopeType == ScopeTypes.SharePoint.SPView) && scope.Properties.ContainsKey(EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListID))
            {
                SPList list = SPContext.Current.Web.Lists[new Guid(scope.Properties[EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListID])];
                //Run RegEx match against list title
                if(rx.IsMatch(list.Title)){
                    //Check if Document Library Index Screen OR List Item Detail Screen
                    if ((scope.ScopeType == ScopeTypes.SharePoint.SPListItem_Details && list.BaseType != SPBaseType.DocumentLibrary) || (scope.ScopeType == ScopeTypes.SharePoint.SPView && list.BaseType == SPBaseType.DocumentLibrary))
                    {
                        //If not a document library, you are on a detail screen of a list item
                        if (list.BaseType != SPBaseType.DocumentLibrary)
                        {
                            SPListItem item = list.GetItemById(int.Parse(scope.Properties[EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListItemID]));
                            //create the action
                            var action = new ActionItem("custom", "SketchCapture")
                            {
                                ClickAction = new EntreeClickActionObject(this)
                                {
                                    TargetContextMenu = true
                                },
                                IconUrl = Icon,
                                Title = "Attach Sketch",
                                Sequence = 999
                            };

                            action.ClickAction["ListGuid"] = list.ID.ToString();
                            action.ClickAction["ListItemId"] = item.ID.ToString();
                            action.ClickAction["savetype"] = "attachment";
                            //add action to the action tray
                            actionItems.Items.Add(action);
                        }
                        else
                        {
                            //this action will be created if you are on a Document Library Index screen
                            var action = new ActionItem("custom", "SketchCapture")
                            {
                                ClickAction = new EntreeClickActionObject(this)
                                {
                                    TargetContextMenu = true
                                },
                                IconUrl = Icon,
                                Title = "Add Sketch",
                                Sequence = 999
                            };

                            action.ClickAction["ListGuid"] = list.ID.ToString();
                            action.ClickAction["ListItemId"] = "0";
                            action.ClickAction["savetype"] = "document";
                            actionItems.Items.Add(action);
                        }
                    }
                }
            }

        }

        public override void QueryList(EntreeScopeObject scope, EntreeListObject output)
        {
            output.ListStyle = EntreeListStyles.context_menu;
            output.ListTitle = "Add Sketch";

            output.ActionScope.ScopeType = "SketchCapture";
            //Check for save property, means the user has clicked the save button
            if (scope.Properties.ContainsKey("save"))
            {
                string filename = scope.FormProperties["filename"] + ".png";
                //Get Base64 encoded image, removing unused header info
                string base64img = scope.FormProperties["sketch"].Replace("data:image/png;base64,", "");
                SPList list = SPContext.Current.Web.Lists[new Guid(scope.Properties["ListGuid"])];
                //If attaching to a list item >>>>>
                if (scope.Properties["savetype"] == "attachment")
                {
                    SPListItem itm = list.GetItemById(int.Parse(scope.Properties["ListItemId"]));
                    try
                    {
                        SPContext.Current.Web.AllowUnsafeUpdates = true;

                        byte[] bytes = System.Convert.FromBase64String(base64img);
                        itm.Attachments.Add(filename, bytes);
                        itm.Update();
                        SPContext.Current.Web.AllowUnsafeUpdates = false;
                        output.ActionScope.TransferToApplication = true;
                    }
                    catch (Exception er)
                    {
                        output.ListTitle = er.ToString();
                    }
                }
                else
                {
                    //This will upload the drawing to a document library
                    try
                    {
                        SPContext.Current.Web.AllowUnsafeUpdates = true;

                        byte[] bytes = System.Convert.FromBase64String(base64img);

                        SPFolder f = list.RootFolder;
                        SPFile doc = f.Files.Add(filename, bytes, true);
                        f.Update();
                        SPContext.Current.Web.AllowUnsafeUpdates = false;
                        output.ActionScope.TransferToApplication = true;
                    }
                    catch (Exception er)
                    {
                        output.ListTitle = er.ToString();
                    }
                }
            }
            else
            {
                //Initial screen loaded from the action
                EntreeListGroup grp = output.AddListGroup();
                grp.ListGroupStyle = EntreeListGroupStyles.list;
                //Add a textbox to contain the filename
                EntreeTextBox fn = grp.AddFormItem<EntreeTextBox>("filename");
                fn.Name = "File Name";
                fn.Value = "Sketch-" + DateTime.Now.Ticks.ToString();
                //Add the custom Canvas control
                grp = output.AddListGroup("Sketch in the Box");
                EntreeFormItem canvas = grp.AddFormItem("sketch");
                canvas.ListItemStyle = "Sketch.Canvas";

                //Add Palette
                EntreeListItem p = grp.AddListItem();
                p.ListItemStyle = "Canvas.Palette";

                //Add the save button
                ActionItem save = new ActionItem();
                save.IconUrl = "/_layouts/images/EntreeServer/inc/at/at-save-32.png";
                save.ActionId = "SaveSketch";
                save.Title = "Save Sketch";
                save.ClickAction = new EntreeClickActionObject(this)
                {
                    FormSubmit = true,
                    TargetContextMenu = false
                };

                save.ClickAction["save"] = "yes";
                save.ClickAction["ListGuid"] = scope.Properties["ListGuid"];
                save.ClickAction["ListItemId"] = scope.Properties["ListItemId"];
                save.ClickAction["savetype"] = scope.Properties["savetype"];
                output.ActionTray.AddAction(save);

                ActionItem Palette = new ActionItem();
                Palette.ActionId = "OpenPalette";
                Palette.IconUrl = "/_layouts/images/ME.SDK.SketchAction/AddSketch/palette.png";
                Palette.Title = "Palette";
                Palette.ClickAction = new EntreeClientsideClickAction(this)
                {
                    TargetFunction = "OpenPalette"
                };

                output.ActionTray.AddAction(Palette);
            }
        }

        public override string Title
        {
            get
            {
                return "Create Sketch";
            }
        }

        public String Icon
        {
            get
            {
                return "/_layouts/images/ME.SDK.SketchAction/AddSketch/sign.png";
            }
        }

        public override string PluginPath
        {
            get
            {
                return "/_layouts/images/ME.SDK.SketchAction/AddSketch";
            }
        }

        [WebBrowsable(true)]
        [WebDisplayName("RegEx List Match")]
        [WebDescription("Regular Expression for matching lists and libraries you can add sketches to")]
        //Add a config property to match lists/libraries that have sketches enabled
        public string RegExMatch { get; set; }
    }
}
